package codetop.microsoft.T151;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @Author: 18362
 * @Create: 2022-08-17 10:42:37 星期三
 */
class Solution {
    public String reverseWords(String s) {
        Deque<String> dq = new LinkedList<>();
        int start = 0, end = 0;
        for (int i=0; i<s.length(); ++i) {
            if (s.charAt(i) != ' ') {
                start = i;
                break;
            }
        }
        for (int i=s.length()-1; i>=0; --i) {
            if (s.charAt(i) != ' ') {
                end = i+1;
                break;
            }
        }
        while (start < end) {
            int i = start, j = start;
            while (j < end && s.charAt(j) != ' ')
                j++;
            StringBuilder sb = new StringBuilder();
            for (int k=i; k<j; ++k)
                sb.append(s.charAt(k));
            dq.push(sb.toString());
            start = j + 1;
            while (start < end && s.charAt(start) == ' ')
                start++;
        }
        StringBuilder sb = new StringBuilder();
        while (true) {
            sb.append(dq.pop());
            if (dq.size() > 0)
                sb.append(' ');
            else
                break;
        }
        return sb.toString();
    }
}